//
//  RootViewController.m
//  WWXELuShang
//
//  Created by 王涛 on 15/12/17.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "RootViewController.h"
#import "HeadView.h"
#import "FirstCollectionViewCell.h"
#import "SecondCollectionViewCell.h"
#import "Weather.h"
#import "MapClassViewController.h"
#import "UsedCarTableViewController.h"
#import "BillingTableViewController.h"
#import "MainNewsViewController.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "RadioViewController.h"
#import "ParkingViewController.h"

@interface RootViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSArray *nameArray;
@property (nonatomic, strong) NSArray *serverArray;
@property (nonatomic, strong) Weather *weater;
@property (nonatomic, strong) HeadView *headerView;
@property (nonatomic, strong) UICollectionReusableView *header;
@property (nonatomic, strong) NSMutableArray *array;//周边服务
@end

@implementation RootViewController

//解析天气
- (void)jsonWeather {
    NSURL *url = [NSURL URLWithString:kWeather];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (data.length == 0) {
            self.headerView = [[HeadView alloc] initWithFrame:(CGRectMake(0, 0, kWidth, kHeight / 4.7))];
            self.headerView.backgroundColor = [UIColor whiteColor];
            [self.header addSubview:self.headerView];
            return ;
        }else {
            NSDictionary *root = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSDictionary *dic1 = root[@"result"];
            self.weater = [Weather setValuesWithDictionary:dic1[@"items"][0]];
            self.headerView = [[HeadView alloc] initWithFrame:(CGRectMake(0, 0, kWidth, kHeight / 4.7))];
            self.headerView.backgroundColor = [UIColor whiteColor];
            self.headerView.weather = self.weater;
            [self.header addSubview:self.headerView];
        }
        [self.collectionView reloadData];
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self jsonWeather];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemRefresh) target:self action:@selector(addQuery)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"discover_smart_category_selected@2x.png"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)]style:(UIBarButtonItemStyleDone) target:self action:@selector(pushDrawer)];
    
    //创建一个布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;//同一行中各元素之间距离
    flowLayout.minimumLineSpacing = 0;//行距
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, kHeight / 44.47, 0);//分区内边距
    CGFloat itemWidth = kWidth / 3;
    CGFloat itemHeight = kWidth / 4;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//竖直滚动
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];//创建collectionView对象，并赋值布局
    
    self.collectionView.backgroundColor = kBackGroundColor;
    //设置数据源和代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    //注册单元格
    [self.collectionView registerClass:[FirstCollectionViewCell class] forCellWithReuseIdentifier:@"firstCell"];
    [self.collectionView registerClass:[SecondCollectionViewCell class] forCellWithReuseIdentifier:@"secondCell"];
    
    //注册区头
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header2"];
    
    
    [self.view addSubview:self.collectionView];
    
    self.imageArray = [NSMutableArray array];
    for (int i = 1; i < 7; i ++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]];
        [self.imageArray addObject:image];
    }
    self.nameArray = @[@"停车计时器",@"实时路况",@"计费管家",@"电台",@"二手车",@"行车咨询"];
    
    self.serverArray = @[@"加油站",@"4S店",@"交通队",@"洗车",@"汽车改装",@"汽车维修",@"汽车装饰",@"酒店",@"停车场",@"汽车美容",@"银行",@""];
    
    self.array = [NSMutableArray array];
    for (int i = 1; i < 9; i ++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"server%d.png",i]];
        [self.array addObject:image];
    }
    __weak RootViewController *rootVC = self;
    [self.collectionView addHeaderWithCallback:^{
        [rootVC jsonWeather];
        [rootVC.collectionView headerEndRefreshing];
    }];

}

- (void)addQuery {
    [self jsonWeather];
}
//左抽屉
- (void)pushDrawer {
    AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (tempAppdelegate.leftSlideVC.closed) {
        [tempAppdelegate.leftSlideVC openLeftView];
    }else{
        [tempAppdelegate.leftSlideVC closeLeftView];
    }
}

// 数据源方法
//分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}
//分区钟item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.imageArray.count;
    }else {
        return self.serverArray.count;
    }
}
//加载单元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        FirstCollectionViewCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"firstCell" forIndexPath:indexPath];
        cell1.imageView.image = self.imageArray[indexPath.item];
        cell1.nameLabel.text = self.nameArray[indexPath.item];
        return cell1;
    }else {
        SecondCollectionViewCell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"secondCell" forIndexPath:indexPath];
        
        if (indexPath.row < 8) {
            NSArray *viewArray = cell2.contentView.subviews;
            for (UIView *view in viewArray) {
                [view removeFromSuperview];
            }
            UIImageView *iconImage = [[UIImageView alloc] initWithFrame:(CGRectMake(kWidth / 4 / 4, kWidth / 4 / 6, kWidth / 4 / 2, kWidth / 4 / 2))];
            iconImage.image = self.array[indexPath.row];
            
            [cell2.contentView addSubview:iconImage];
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:(CGRectMake(0, kWidth / 4 * 2 / 3, kWidth / 4, kWidth / 4 / 3))];
            nameLabel.font = [UIFont systemFontOfSize:13];
            nameLabel.textAlignment = NSTextAlignmentCenter;
            nameLabel.textColor = [UIColor lightGrayColor];
            nameLabel.text = self.serverArray[indexPath.row];
            [cell2.contentView addSubview:nameLabel];
        }else {
            NSArray *viewArray = cell2.contentView.subviews;
            for (UIView *view in viewArray) {
                [view removeFromSuperview];
            }
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:(CGRectMake(0, kWidth / 10 / 3, kWidth / 4, kWidth / 10 / 3))];
            nameLabel.font = [UIFont systemFontOfSize:13];
            nameLabel.textAlignment = NSTextAlignmentCenter;
            nameLabel.textColor = [UIColor lightGrayColor];
            nameLabel.text = self.serverArray[indexPath.row];
            [cell2.contentView addSubview:nameLabel];
            
        }
        return cell2;
    }
    
}
//选中单元格
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            ParkingViewController *parkingVC = [[ParkingViewController alloc] init];
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:parkingVC];
            navC.navigationBar.barTintColor = kBarColor;
            [navC.navigationBar setTitleTextAttributes:
             @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
            navC.navigationBar.tintColor = [UIColor whiteColor];
            navC.navigationBar.tintColor = [UIColor whiteColor];
            [self presentViewController:navC animated:YES completion:nil];
        }
        if (indexPath.row == 1) {
            MapClassViewController *mapVC = [[MapClassViewController alloc]init];
            mapVC.switchTraffic = YES;
            mapVC.navigationItem.title = self.nameArray[indexPath.row];
            mapVC.view.backgroundColor = [UIColor whiteColor];
            UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:mapVC];
            
            navC.navigationBar.barTintColor = kBarColor;
            navC.navigationBar.translucent = NO;
            [navC.navigationBar setTitleTextAttributes:
             @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
            navC.navigationBar.tintColor = [UIColor whiteColor];
            [self presentViewController:navC animated:YES completion:nil];
        }
        if (indexPath.row == 2) {
            BillingTableViewController *billingTVC = [[BillingTableViewController alloc] init];
            [self presentViewController:billingTVC animated:YES completion:nil];
        }
        if (indexPath.row == 4) {
            UsedCarTableViewController *useCarTVC = [[UsedCarTableViewController alloc] init];
            UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:useCarTVC];
            [self presentViewController:navc animated:YES completion:nil];
        }
        if (indexPath.row == 5) {
            MainNewsViewController *mainNewsVC = [[MainNewsViewController alloc]init];
            UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:mainNewsVC];
            navc.navigationBar.translucent = NO;
            navc.navigationBar.barTintColor = kBarColor;
            [navc.navigationBar setTitleTextAttributes:
             @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
            navc.navigationBar.tintColor = [UIColor whiteColor];
            [self presentViewController:navc animated:YES completion:nil];
            
        }
        
        
        if (indexPath.row == 3) {
            RadioViewController *radioVC = [[RadioViewController alloc]init];
            UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:radioVC];
            
            
            
            [self presentViewController:navC animated:YES completion:nil];
            
        }

        
        
        
        
        NSLog(@"车讯");
    }else {
        MapClassViewController *mapVC = [[MapClassViewController alloc]init];
        mapVC.switchTraffic = NO;
        mapVC.searchString = self.serverArray[indexPath.row];
        mapVC.navigationItem.title = mapVC.searchString;
        mapVC.view.backgroundColor = [UIColor whiteColor];
        UINavigationController *navC = [[UINavigationController alloc]initWithRootViewController:mapVC];
        navC.navigationBar.barTintColor = kBarColor;
        navC.navigationBar.translucent = NO;
        [navC.navigationBar setTitleTextAttributes:
         @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
        navC.navigationBar.tintColor = [UIColor whiteColor];
        [self presentViewController:navC animated:YES completion:nil];
        
        NSLog(@"%@",mapVC.searchString);
    }
}
//加载区头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        self.header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        return self.header;
    }else {
        UICollectionReusableView *header2 = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header2" forIndexPath:indexPath];
        NSArray *array = header2.subviews;
        for (UIView *view in array) {
            [view removeFromSuperview];
        }
        UIView *view = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kWidth, kHeight / 26.68))];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *label1 = [[UILabel alloc] initWithFrame:(CGRectMake(0, 0, kHeight / 222.34, kHeight / 26.68))];
        UIColor *textColor = [UIColor colorWithRed:219 / 255.0 green:50 / 255.0 blue:90 / 255.0 alpha:1];
        label1.backgroundColor = textColor;
        UILabel *label2 = [[UILabel alloc] initWithFrame:(CGRectMake(kWidth / 37.5, kHeight / 166.75, kWidth - 5, kHeight / 33.35))];
        label2.text = @"周边服务";
        label2.font = [UIFont systemFontOfSize:13];
        label2.textColor = [UIColor darkGrayColor];
        [view addSubview:label2];
        [view addSubview:label1];
        [header2 addSubview:view];
        return header2;
    }
    
}
//设置区头高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(kWidth, kHeight / 4.3);
    }else {
        return CGSizeMake(kWidth, kHeight / 26.68);
    }
}
//布局代理
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return UIEdgeInsetsMake(0, 0, kHeight / 44.47, 0);
    }else{
        return UIEdgeInsetsMake(0.5, 0, kHeight / 7, 0);
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat itemWidth = kWidth / 3;
        CGFloat itemHeight = kWidth / 4;
        return CGSizeMake(itemWidth, itemHeight);
    }else {
        if (indexPath.row < 8) {
            CGFloat itemWidth = kWidth / 4;
            CGFloat itemHeight = kWidth / 4;
            return CGSizeMake(itemWidth, itemHeight);
        }else{
            CGFloat itemWidth = kWidth / 4;
            CGFloat itemHeight = kWidth / 10;
            return CGSizeMake(itemWidth, itemHeight);
        }
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
    [super viewWillAppear:animated];
    AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppdelegate.leftSlideVC setPanEnabled:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
